package org.littlesun.management.address;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import lombok.AllArgsConstructor;

import org.apache.commons.lang3.StringUtils;

@AllArgsConstructor
public class ZoneMatcher {

	private MatchResult parent;
	private Collection<City> cities;
	
	public ZoneMatcher(MatchResult parent, City... cities) {
		this(parent, Arrays.asList(cities));
	}
	
	public MatchResult match(String text) {
		MatchResult result = matchZoneName(text);
		if (result.isSuccess() == false) {
			result = matchZoneAlias(text);
		}
		if (result.isSuccess() == false) {
			result.addSuggestions(getSuggestions());
		}
		return result;
	}
	
	private MatchResult matchZoneName(String text) {
		text = text.trim();
		for(City city : cities) {
			for(Zone zone : city.getZones()) {
				if (StringUtils.startsWith(text, zone.getName())) {
					return new MatchResult(parent, zone, zone.getName(), text.substring(zone.getName().length()));
				}
			}
		}
		return new MatchResult(parent, null, "", text);
	}

	private MatchResult matchZoneAlias(String text) {
		text = text.trim();
		for(City city : cities) {
			for(Zone zone : city.getZones()) {
				for(String alias : zone.getAliases()) {
					if (StringUtils.startsWith(text, alias)) {
						return new MatchResult(parent, zone, alias, text.substring(alias.length()));
					}
				}
			}
		}
		return new MatchResult(parent, null, "", text);
	}

	protected List<String> getSuggestions() {
		String matchedOrginalText = parent == null? "" : parent.getFullMatchedOrginalText();
		List<String> names = new ArrayList<String>();
		for(City city : cities) {
			for(Zone zone : city.getZones()) {
				names.add(matchedOrginalText + zone.getName());
			}
		}
		return names;
	}

}
